package com.bmicpd.gzh.service;

import com.bmicpd.gzh.pojo.RealTimePushMessagePojo;
import com.bmicpd.gzh.util.FileSaveUtils;
import com.bmicpd.gzh.util.GzhDateTimeUtils;
import com.bmicpd.gzh.util.PatternUtils;
import com.bmicpd.gzh.util.PhantomJsUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;

/**
 *
 * @author ytree
 */
@Service
public class RealTimePushMessageService {

    private final Logger logger = LoggerFactory.getLogger(RealTimePushMessageService.class);
    private final String GZHID_REGEX = "<span class=\"profile_meta_value\">([a-zA-Z0-9_-]*)</span>";
    private final String TIMESTAMP_REGEX = "ct = \"([0-9]+)\";";

    @Value("${get.html.timeout}")
    private int timeout;

    @Value("${phantomjs.path}")
    private String phantomjsPath;

    @Value("${image.dir}")
    private String imgDir;

    @Value("${html.dir}")
    private String htmlDir;

    @Value("${image.postfix}")
    private String imgPostfix;

    @Value("${html.postfix}")
    private String htmlPostfix;

    /**
     * 通过原文url获取源文件内容
     * @param messagePojo 消息对象
     * @param uuid 文章在es中的唯一标识
     * @return Map<String, String>
     */
    public Map<String, String> getContent(RealTimePushMessagePojo messagePojo, String uuid){

        // 公众号标题hash值
        int hashCode = messagePojo.getApp_title().hashCode();
        // image保存路径
        String imagePath = null;
        // html保存路径
        String htmlPath = null;

        // java + phantomjs --> html --> image
        PhantomJSDriver phantomJsDriver = PhantomJsUtils.getPhantomJsDriver(phantomjsPath);
        ArrayList<String> imageUrlList = Lists.newArrayList();
        String appUrl = messagePojo.getApp_url();

        // 网速不好时，会报空指针异常
        Document document = null;
        try {
            document = Jsoup.parse(new URL(appUrl), timeout);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将html转换成图片 gzh id <span class="profile_meta_value">newlandplanning</span>
        String gzhId = PatternUtils.getMatchData(document.toString(),
                GZHID_REGEX, 1);

        FileSaveUtils.createDir(imgDir + gzhId);

        imagePath = imgDir +"\\"+ gzhId +"\\"+ hashCode + imgPostfix;

        try {
            PhantomJsUtils.renderer2Image(messagePojo.getApp_url(), phantomJsDriver,
                    "png", imagePath);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        // 保存html文件
        FileSaveUtils.createDir(htmlDir + gzhId);
        htmlPath = htmlDir +"\\"+ gzhId + "\\" + hashCode + htmlPostfix;
        FileSaveUtils.saveFile(htmlPath, document.outerHtml());

        String rawContent = document.getElementById("js_content").toString();
        // 公众号内容
        String content = rawContent.replaceAll("<.*?>", "");
        content = content.replaceAll("\n", "");

        // 发布时间
        String timestamp = PatternUtils.getMatchData(document.toString(),
                TIMESTAMP_REGEX, 1);

        String date = GzhDateTimeUtils.timestamp2Date(timestamp);
        String datetime = GzhDateTimeUtils.timestamp2DateTime(timestamp);
        logger.info("date : " + date +", datetime : "+ datetime);

        // 缩略图url
        Elements imgs = document.getElementsByTag("img");
        for (Element img : imgs){

            // 用于记录循环次数
            int temp = 0;

            String imgUrl = img.attr("data-src");
            if(null == imgUrl || imgUrl.contains("wx_fmt=gif") || "".equals(imgUrl)){
                continue;
            }
            imageUrlList.add(imgUrl);
            logger.info(temp +"; "+"toString"+imgUrl);
            temp++;
        }

        logger.info("content : " + content);
        logger.info("title : " + messagePojo.getApp_title());

        Map<String, String> sourceMap = Maps.newHashMap();
        sourceMap.put("irSid", uuid);
        sourceMap.put("irChannel", messagePojo.getApp_name());
        sourceMap.put("irAbstract", messagePojo.getApp_desc());
        sourceMap.put("irUrlName", messagePojo.getApp_url());
        sourceMap.put("irSiteName", messagePojo.getApp_name());
        sourceMap.put("irContent", content);
        sourceMap.put("irUrlDate", date);
        sourceMap.put("irUrlTime", datetime);
        sourceMap.put("irUrlTitle", messagePojo.getApp_title());
        sourceMap.put("irImageUrl", imageUrlList.get(0));
        sourceMap.put("irDetailPage", htmlPath);
        sourceMap.put("irGzh2ImgUrl", imagePath);

        return sourceMap;
    }

}
